<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据号" prop="hDanhao">
        <el-input
          v-model="queryParams.hDanhao"
          placeholder="请输入单据号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库日期" prop="hShijian">
        <el-date-picker clearable
          v-model="queryParams.hShijian"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择入库日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="仓库" prop="kuId">
        <el-input
          v-model="queryParams.kuId"
          placeholder="请输入仓库"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['jiuzai:wuzihuisou:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
    <!-- 新增的查看按钮 -->
    <el-button
      type="info"
      plain
      icon="View"
      @click="handleBatchView"
      v-hasPermi="['jiuzai:wuziruku:query']"
    >查看</el-button>
  </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['jiuzai:wuzihuisou:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['jiuzai:wuzihuisou:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['jiuzai:wuzihuisou:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="wuzihuisouList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="hId" />
      <el-table-column label="入库人" align="center" prop="yId" >
        <template #default="scope">
          <span v-if="scope.row.yId===scope.row.yId">{{ scope.row.table12.yName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据号" align="center" prop="hDanhao" />
      <el-table-column label="入库日期" align="center" prop="hShijian" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.hShijian, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库" align="center" prop="kuId" >
        <template #default="scope">
          <span v-if="scope.row.kuId===scope.row.kuId">{{ scope.row.cangku.kuName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['jiuzai:wuzihuisou:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['jiuzai:wuzihuisou:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物资回收对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="wuzihuisouRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户id" prop="yId">
          <!-- 下拉框 -->
           <el-select v-model="form.yId" placeholder="请选择用户id">
              <el-option
                v-for="item in wuziList"
                :key="item.yId"
                :label="item.yName"
                :value="item.yId"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="单据号" prop="hDanhao">
          <el-input v-model="form.hDanhao" placeholder="请输入单据号" />
        </el-form-item>
        <el-form-item label="入库日期" prop="hShijian">
          <el-date-picker clearable
            v-model="form.hShijian"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择入库日期">
          </el-date-picker>
        </el-form-item>
        <!-- 下拉框 -->
        <el-form-item label="仓库" prop="kuId">
          <el-select v-model="form.kuId" placeholder="请选择仓库">
              <el-option
                v-for="item in cangkuList"
                :key="item.kuId"
                :label="item.kuName"
                :value="item.kuId"
              />
            </el-select>
        </el-form-item>
          <!-- 物资详细 -->
          <el-form-item label="物资详细" prop="rukuXiangqing">
          <el-button 
      type="success" 
      plain 
      icon="Select" 
      @click="wuzixinxi"
      v-hasPermi="['jiuzai:wuzixinxi:query']"
    >选择物资</el-button>
      <!-- 显示已选择的物资明细 -->
      <el-table :data="form.mingxiList || []" border style="margin-top: 10px;">
      <el-table-column prop="wuziMing" label="物资名称" />
      <el-table-column prop="wuziGuige" label="规格" />
      <el-table-column prop="mingleib" label="类别" />
      <el-table-column label="数量" prop="wuziShu" width="120">
    <template #default="scope">
      <el-input 
        v-model="scope.row.wuziShu" 
        type="number"
        min="1"
        @change="handleQuantityChange(scope.row)"
      />
    </template>
  </el-table-column>
      <el-table-column label="操作" width="80" align="center">
        <template #default="scope">
          <el-button link type="danger" icon="Delete" @click="removeMingxi(scope.$index)" />
        </template>
      </el-table-column>
    </el-table>
         </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="物资回收详细" v-model="viewOpen" width="700px" append-to-body>
  <div style="display: flex; flex-direction: column; max-height: 70vh;">
    <!-- 主表信息（固定不滚动） -->
    <div style="flex-shrink: 0; padding: 20px; overflow-y: auto;">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="序号">{{ viewForm.hId }}</el-descriptions-item>
        <el-descriptions-item label="仓库">{{ viewForm.cangku.kuName }}</el-descriptions-item>
        <el-descriptions-item label="入库人">{{ viewForm.table12.yName }}</el-descriptions-item>
        <el-descriptions-item label="单据号">{{ viewForm.hDanhao }}</el-descriptions-item>
      </el-descriptions>
    </div>

<!-- 物资明细表格（可左右滚动） -->
<div style="flex-grow: 1; overflow: hidden; display: flex; flex-direction: column; padding: 0 20px 20px;">
  <div style="font-weight: bold; margin: 10px 0 5px 0;">物资明细</div>
  <div style="flex-grow: 1; overflow: auto;">
    <el-table 
    :data="Array.isArray(viewForm.baofeimingxi) ? viewForm.baofeimingxi : viewForm.baofeimingxi ? [viewForm.baofeimingxi] : []" 
  border 
  size="small"
  style="width: 100%;">
  <el-table-column label="序号" align="center" prop="baomingId" />
  <el-table-column label="物资名称" align="center" prop="wuziMing" />
  <el-table-column label="规格" align="center" prop="wuziGuige" />
  <el-table-column label="数量" align="center" prop="wuziShu"> 
  </el-table-column>
</el-table>

  </div>
</div>
  </div>

  <template #footer>
    <div class="dialog-footer">
      <el-button @click="viewOpen = false">关 闭</el-button>
    </div>
  </template>
</el-dialog>


<!-- 选择物资信息弹窗 -->
<el-dialog 
  title="选择物资" 
  v-model="selectDialogVisible" 
  width="700px"
  append-to-body>
  
  <el-table :data="wuzixinxiList" border style="width: 100%">
      <el-table-column label="序号" align="center" prop="wuziId" />
      <el-table-column label="物资编号" align="center" prop="wuziBianhao" />
      <el-table-column label="物资名称" align="center" prop="wuziName" />
      <el-table-column label="物资类别" align="center" prop="leibieId">
        <template v-slot="scope">
          <span v-if="scope.row.leibieId === scope.row.wuzileibie.leiId">
            {{ scope.row.wuzileibie.leiName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="是否为回收的物资" align="center" prop="wuziHui" />
      <el-table-column label="物资单位" align="center" prop="wuziDanwei" />
    <el-table-column label="操作" width="120" align="center">
      <template #default="scope">
        <el-button 
          type="primary" 
          size="small" 
          @click="selectWuzi(scope.row)">
          选择
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <template #footer>
    <div class="dialog-footer">
      <el-button @click="selectDialogVisible = false">关闭</el-button>
    </div>
  </template>
</el-dialog>


  </div>
</template>
 
<script setup name="Wuzihuisou">
import { listWuzihuisou, getWuzihuisou, delWuzihuisou, addWuzihuisou, updateWuzihuisou } from "@/api/jiuzai/wuzihuisou"
import { addBaofeimingxi, getBaofeimingxi , updateBaofeimingxi,  listBaofeimingxi  } from "@/api/jiuzai/baofeimingxi" 
import { addCangkumingxi } from "@/api/jiuzai/cangkumingxi"
import { listWuzixinxi, getWuzixinxi, updateWuzixinxi } from "@/api/jiuzai/wuzixinxi";
import { listCangku } from "@/api/cangku/cangku"
import { listWuzi } from  "@/api/jiuzai/wuzi"

const { proxy } = getCurrentInstance()

const wuzixinxiList = ref([])
const wuzihuisouList = ref([])
const wuziList = ref({})
const cangkuList = ref({})
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const viewForm = ref({}) // 新增查看表单数据
const viewOpen = ref(false) // 新增查看对话框状态
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const selectDialogVisible = ref(false) 

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    hDanhao: null,
    hShijian: null,
    kuId: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询物资回收列表 */
function getList() {
  loading.value = true
  listWuzihuisou(queryParams.value).then(response => {
    wuzihuisouList.value = response.rows
    console.log(wuzihuisouList)
    total.value = response.total
    loading.value = false
  })
}


/** 查询全部物资信息按钮 */
function wuzixinxi() {
  selectDialogVisible.value = true
  loading.value = true
  listWuzixinxi(queryParams.value).then(response => {
    wuzixinxiList.value = response.rows
    console.log(wuzixinxiList)
    loading.value = false
  })
}

// 选择物资
function selectWuzi(row) {
  form.hWuziId = row.wuziId
  selectDialogVisible.value = false
  getWuzixinxi(row.wuziId).then(response => {
    const wuziDetail = response.data
    
    // 确保明细列表存在
    if (!form.value.mingxiList) {
      form.value.mingxiList = []
    }
    
    // 添加物资到明细列表
    form.value.mingxiList.push({
      wuziId: wuziDetail.wuziId,          // 物资ID
      wuziMing: wuziDetail.wuziName,      // 物资名称
      wuziGuige: wuziDetail.wuziDanwei,    // 规格
      mingleib: wuziDetail.wuzileibie.leiName,
      wuziShangjia: wuziDetail.wuziShangjia, // 供应商
      wuziShu: 1,                    // 默认数量1
      mingDanjia: wuziDetail.wuziGuige,  // 单价
    })
    console.log('添加的物资明细:', form.value.mingxiList[form.value.mingxiList.length - 1])
  }).catch(error => {
    console.error('获取物资详情失败:', error)
    proxy.$message.error('获取物资详情失败')
  })
}


/** 查看按钮操作 */
function handleBatchView() {
  if (ids.value.length === 0) {
    proxy.$message.warning("请先选择要查看的记录");
    return;
  }
  if (ids.value.length > 1) {
    proxy.$message.warning("只能选择一条记录查看");
    return;
  }
  
  const h_id = ids.value[0];
  getWuzihuisou(h_id).then(response => {
    viewForm.value = response.data;
    console.log('查看数据详情:', response.data); // 添加调试输出
    viewOpen.value = true;
  });
  
}

function getCangkuList() {
  loading.value = true
  listCangku(queryParams.value).then(response => {
    cangkuList.value = response.rows
    // console.log(cangkuList.value)
    loading.value = false
  })
}

function getjueseList() {
  loading.value = true
  listWuzi(queryParams.value).then(response => {
    wuziList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}


onMounted(() => {
  getCangkuList()
  getjueseList()
})


// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    hId: null,
    yId: null,
    hDanhao: null,
    hCangku: null,
    hShijian: null,
    kuId: null,
    shenheDate: null,
    shenheUser: null,
    shenheBeizhu: null,
    shenheZhuangtai: null,
    mingxiList: [], // 初始化明细列表
  }
  proxy.resetForm("wuzihuisouRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.hId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加物资回收"
  // 确保只生成一次单据号
  if (!form.value.hDanhao) {
    const now = new Date()
    const timePart = now.toISOString().replace(/[-:T.]/g, '').slice(2, 14)
    form.value.hDanhao = `RK${timePart}`
  }
  
  console.log('新增表单已初始化', form.value) // 调试用
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  const hId = row.hId || ids.value[0];  // 正确定义 hId
  loading.value = true;

  try {
    // 1. 获取主表数据
    const mainRes = await getWuzihuisou(hId);
    
    // 2. 获取明细数据（使用 hId 查询关联的明细）
    const detailRes = await listBaofeimingxi({ hId: hId });
    
    // 3. 合并数据到表单
    form.value = {
      ...mainRes.data,
      mingxiList: (detailRes.rows || []).map(item => ({
        baomingId: item.baomingId,
        wuziId: item.wuziId,
        wuziMing: item.wuziMing || '未命名物资',
        wuziGuige: item.wuziGuige || '',
        wuziShu: item.wuziShu || 1,
        mingDanjia: item.mingDanjia || 0,
        hId: item.hId
      }))
    };

    open.value = true;
    title.value = "修改物资回收";
    
    console.log('表单数据:', form.value);
  } catch (error) {
    console.error("加载数据失败:", error);
    proxy.$modal.msgError(`加载失败: ${error.response?.data?.message || error.message}`);
  } finally {
    loading.value = false;
  }
}
/** 提交按钮 */
async function submitForm() {
  proxy.$refs["wuzihuisouRef"].validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        
        // 1. 准备主表数据
        const mainData = { ...form.value };
        delete mainData.mingxiList;
        delete mainData.cangku;
        delete mainData.table12;
        
        // 2. 提交主表
        const res = form.value.hId 
          ? await updateWuzihuisou(mainData) 
          : await addWuzihuisou(mainData);
        
        const currentHId = form.value.hId || res.data?.hId;
        if (!currentHId) throw new Error("获取回收ID失败");
        
        // 3. 处理明细数据
        if (form.value.mingxiList?.length) {
          await processMingxiList(currentHId);
          
          // 4. 更新物资信息表中的数量
          await updateWuziQuantities(form.value.mingxiList);
        }
        
        proxy.$modal.msgSuccess("操作成功");
        open.value = false;
        getList();
      } catch (error) {
        console.error("提交失败:", error);
        proxy.$modal.msgError(`操作失败: ${error.message}`);
      } finally {
        loading.value = false;
      }
    }
  });
}

async function updateWuziQuantities(mingxiList) {
  try {
    for (const item of mingxiList) {
      const wuziRes = await getWuzixinxi(item.wuziId);
      const currentWuzi = wuziRes.data;
      
      // 确保 currentWuzi.wuziShu 和 item.wuziShu 是数字
      const currentQuantity = Number(currentWuzi.wuziShu) || 0;
      const addedQuantity = Number(item.wuziShu) || 0;
      const newQuantity = currentQuantity + addedQuantity;
      
      await updateWuzixinxi({
        ...currentWuzi,
        wuziShu: newQuantity  // 确保存储的是数字
      });
    }
  } catch (error) {
    console.error("更新物资数量失败:", error);
    throw new Error("更新物资数量失败");
  }
}
async function processMingxiList(hId) {
  try {
    if (!hId) {
      throw new Error("缺少主表ID")
    }

    const results = []
    const validMingxi = form.value.mingxiList.filter(item => 
      item.wuziId && item.wuziShu > 0
    )

    if (validMingxi.length === 0) {
      throw new Error("请至少添加一条有效的物资明细")
    }
    
    for (const item of validMingxi) {
      // 确保每个明细项都有必要字段
      const detailData = {
        baomingId: item.baomingId || undefined, // 新增时不需要
        wuziId: Number(item.wuziId),
        wuziMing: item.wuziMing || '',
        wuziGuige: item.wuziGuige || '',
        wuziShu: Number(item.wuziShu) || 1,
        mingDanjia: Number(item.mingDanjia) || 0,
        hId: Number(hId)
      }
      
      console.log('处理明细数据:', detailData)
      
      try {
        let res
        if (item.baomingId) {
          // 更新已有明细
          res = await updateBaofeimingxi(detailData)
        } else {
          // 新增明细
          res = await addBaofeimingxi(detailData)
        }
        results.push(res)
      } catch (error) {
        console.error(`处理明细项失败: ${item.wuziMing}`, error)
        throw new Error(`处理物资[${item.wuziMing}]失败: ${error.response?.data?.message || error.message}`)
      }
    }
    
    console.log('明细处理结果:', results)
    return results
  } catch (error) {
    console.error('处理明细失败:', error)
    throw error
  }
}

// function submitForm() {
//   proxy.$refs["wuzihuisouRef"].validate(valid => {
//     if (valid) {
//       if (form.value.hId != null) {
//         updateWuzihuisou(form.value).then(response => {
//           proxy.$modal.msgSuccess("修改成功")
//           open.value = false
//           getList()
//         })
//       } else {
//         addWuzihuisou(form.value).then(response => {
//           proxy.$modal.msgSuccess("新增成功")
//           open.value = false
//           getList()
//         })
//       }
//     }
//   })
// }

/** 删除按钮操作 */
function handleDelete(row) {
  const _hIds = row.hId || ids.value
  proxy.$modal.confirm('是否确认删除物资回收编号为"' + _hIds + '"的数据项？').then(function() {
    return delWuzihuisou(_hIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('jiuzai/wuzihuisou/export', {
    ...queryParams.value
  }, `wuzihuisou_${new Date().getTime()}.xlsx`)
}



watch(() => form.value.hShijian, (newDate) => {
  if (!form.value.hDanhao && newDate) {
    // 当入库日期变化且单据号为空时自动生成
    const datePart = newDate.replace(/-/g, '').slice(2) // 获取YYMMDD
    const randomPart = Math.floor(Math.random() * 9000 + 1000) // 4位随机数
    form.value.hDanhao = `RK${datePart}${randomPart}`
  }
}, { immediate: true })
getList()
</script>
